package cn.netuo.bumbersoll;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.rooten.ctrl.EditDialog;
import com.rooten.frame.AppActivity;
import com.rooten.util.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.netuo.bumbersoll.entity.AreaItem;
import cn.netuo.bumbersoll.entity.BumberSollBaseResponse;
import cn.netuo.bumbersoll.entity.Cmd;
import cn.netuo.bumbersoll.entity.Page;
import cn.netuo.bumbersoll.http.PageResponse;
import cn.netuo.bumbersoll.util.BsUtil;
import lib.grasp.helper.LinearLayoutHelper;
import lib.grasp.http.volley.VolleyHelper;
import lib.grasp.util.L;
import lib.grasp.util.TOAST;
import lib.grasp.widget.MessageBoxGrasp;
import lib.grasp.widget.diaglog.RadioOneEntity;

/**
 * 1. 采集系统业务编号
 * 2. 选择区域类型
 *
 */
public class InputBizIdActivity extends AppActivity implements View.OnClickListener {
    private View mView;
    private String mBleAddr;
    private LinearLayout mContainer;
    private TextView mTvArea;
    private TextView mBizId;

    private String mInputBizId;
    /** 用户所选择的区域 */
    private RadioOneEntity mRadioOne;
    /** 服务器返回的区域列表 */
    private List<AreaItem> mAreaListFromS = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mView = LayoutInflater.from(this).inflate(R.layout.activity_input, null);
        installView(mView, 1);

        initView();
        initData();
    }

    @Override
    protected void initActionMenu(MenuItem item) {
        super.initActionMenu(item);
        item.setVisible(false);
        setTitle("采集设备编号");
        mToolbar.setNavigationIcon(null);
    }

    /** 初始化布局 */
    private void initView(){
        mContainer = mView.findViewById(R.id.ll_container);

        LinearLayoutHelper.addTransportSpace(this, mContainer, 20);
        mTvArea = LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "区域类型", "", "", "01", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        mBizId = LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "业务编号", "", "", "02", true);

        mView.findViewById(R.id.btn_dir).setOnClickListener(this);
    }

    /** 初始化参数 */
    private void initData() {
        mBleAddr = Util.getString(getIntent(), "bleAddr");
        doLoadArea();
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_dir){
            doBind();
            return;
        }

        switch ((String)v.getTag()) {
            case "01": {
                doSelectAreaId();
                break;
            }
            case "02": {
                EditDialog.edit(this, "请输入二维码下方的编号", text -> {
                    if(TextUtils.isEmpty(text)) {
                        TOAST.showShort(InputBizIdActivity.this, "编号输入有误!");
                        return;
                    }
                    mInputBizId = text;
                    mBizId.setText(mInputBizId);
                });
                break;
            }
        }
    }

    private void doSelectAreaId(){
        MessageBoxGrasp.radioOne(this, "请选择点位类型", true, AreaItem.area2Radio(mAreaListFromS), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object o = v.getTag();
                if(!(o instanceof RadioOneEntity)) return;
                mRadioOne = (RadioOneEntity) o;
                mTvArea.setText(mRadioOne.name);
            }
        });
    }

    /**
     * 获取区域信息
     */
    private void doLoadArea() {
        VolleyHelper.with(this)
                .setURL(BizConstant.GET_AREA_INFO)
                .setMethod(Request.Method.GET)
                .setHeadParam(new HashMap<>())
                .setParam(new HashMap<>())
                .setIsShowProg(true, "正在获取区域信息")
                .setSwip(null)
                .onSuccess((Response.Listener<PageResponse<Page>>) response -> {
                    if (response == null || response.code != 0) {
                        TOAST.showShort(InputBizIdActivity.this, "获取区域信息失败" + ((response != null && !TextUtils.isEmpty(response.msg)) ? "," + response.msg : ""));
                        return;
                    }
                    L.logOnly("获取区域信息-成功");
                    mAreaListFromS.clear();
                    mAreaListFromS.addAll(response.data.list);
                })
                .onError(volleyError -> TOAST.showShort(this, "获取区域信息失败"))
                .execute(new TypeToken<PageResponse<Page>>() {
                }.getType());
    }

    /**
     * 绑定
     */
    private void doBind() {
        if(mRadioOne == null) {
            TOAST.showShort(this, "请先选择区域类型!");
            return;
        }
        if(TextUtils.isEmpty(mInputBizId)) {
            TOAST.showShort(this, "请输入桌面二维码下方的编号!");
            return;
        }

        // 如果DB没有订阅的MQTT的主题,就去网络查
        Map<String, String> map = new HashMap<>();
        map.put("id"        , mInputBizId);       // 扫码内容
        map.put("androidId" , BsUtil.getDeviceId(this)); // android 设备ID
        map.put("bleId"     , mBleAddr);    // BLE 设备ID
        map.put("areaId"    , mRadioOne.id);    // 区域类型ID

        map.put("type"      , "1");     // android 设备类型
        map.put("remark"    , "");      // remark

        VolleyHelper.with(this)
                .setURL(BizConstant.POST_REGIST)
                .setMethod(Request.Method.GET)
                .setHeadParam(new HashMap<>())
                .setParam(map)
                .setIsShowProg(true, "正在获取订阅主题信息")
                .setSwip(null)
                .onSuccess((Response.Listener<BumberSollBaseResponse>) response -> {
                    if (response == null || response.code != 0 || response.topic == null || response.allCmd == null || response.allCmd.size() == 0) {
                        TOAST.showShort(InputBizIdActivity.this, "获取失败" + ((response != null && !TextUtils.isEmpty(response.msg)) ? "," + response.msg : ""));
                        return;
                    }
                    L.logOnly("从服务器中获取订阅主题-成功");
                    doSyncDB(response);
                })
                .onError(volleyError -> TOAST.showShort(this, "获取失败"))
                .execute(new TypeToken<BumberSollBaseResponse>() {
                }.getType());
    }

    /**
     * 系统初始化
     * 1. 将数据存入DB
     * 2. 将数据复制到内存
     */
    private void doSyncDB(BumberSollBaseResponse response) {
        String topic        = response.topic;
        String areaId       = response.entity.areaId;
        String bleId        = response.entity.bleId;
        String bizId        = response.entity.id;
        App.getApp().getTableMgr().getTbArg().importArg(BizConstant.ARG_MQTT_TOPIC_KEY  , topic);           // mqtt订阅主题
        App.getApp().getTableMgr().getTbArg().importArg(BizConstant.ARG_BLE_ADDR_KEY    , bleId);           // 目标蓝牙addr
        App.getApp().getTableMgr().getTbArg().importArg(BizConstant.ARG_AREA_ID_KEY     , areaId);          // 区域ID
        App.getApp().getTableMgr().getTbArg().importArg(BizConstant.ARG_BIZ_ID_KEY      , bizId);           // 业务ID

        List<Cmd> cmds = response.allCmd;
        for (Cmd cmd : cmds) {
            // 将所有的命令以命令别名为主键存入DB
            App.getApp().getTableMgr().getTbCmd().importArg(cmd);  // 存入数据库

            // 将关电指令存起来
            if(TextUtils.equals(BizConstant.REQUEST_NAME_AUTO_POWEROFF, cmd.requestName)) BizConstant.REQUEST_NAME_AUTO_POWEROFF_VALUE = cmd.targetValue.get(0);
        }
        switchToMain();
        TOAST.showLong(this, "注册成功!");
    }

    private void switchToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
